package org.example.Page;

import org.example.POJO.online.MyMessage;
import org.example.POJO.online.User;
import org.example.Utils.SocketUtil;
import org.example.Utils.UserFileManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;

public class LoginFrame extends JFrame implements ActionListener {
    private JTextField usernameField;
    private JTextField serverField;
    private JLabel avatarLabel;
    private String avatarPath = "picture/face/1-1.gif";

    private Socket socket;
    private UserFileManager userFileManager ;

    public LoginFrame() {
        setTitle("Java象棋");
        setSize(400, 545);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 用户名和服务器地址输入框
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new GridLayout(2, 1));
        JPanel usernamePanel = new JPanel(new BorderLayout());
        JLabel usernameLabel = new JLabel("用户名:");
        this.usernameField = new JTextField(20);
        usernamePanel.add(usernameLabel, BorderLayout.WEST);
        usernamePanel.add(this.usernameField, BorderLayout.CENTER);
        inputPanel.add(usernamePanel);
        JPanel serverPanel = new JPanel(new BorderLayout());
        JLabel serverLabel = new JLabel("服务器地址:");
        this.serverField = new JTextField(20);
        serverPanel.add(serverLabel, BorderLayout.WEST);
        serverPanel.add(this.serverField, BorderLayout.CENTER);
        inputPanel.add(serverPanel);

        // 头像标签
        avatarLabel = new JLabel();
        ImageIcon avatarIcon = new ImageIcon("picture/face/1-1.gif");
        Image scaledImage = avatarIcon.getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH); // 调整为30x30像素
        avatarLabel.setIcon(new ImageIcon(scaledImage));
        avatarLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        // 创建一个 JLabel 来显示“头像”文本
        JLabel avatarTextLabel = new JLabel("头像");

        // 创建一个 JPanel 来包含头像文本标签和头像标签
        JPanel avatarPanel = new JPanel();
        avatarPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5)); // 使用 FlowLayout 并设置间距

        // 将头像文本标签和头像标签添加到 avatarPanel 中
        avatarPanel.add(avatarTextLabel);
        avatarPanel.add(avatarLabel);

        // 添加组件到主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(inputPanel, BorderLayout.NORTH);
        mainPanel.add(avatarPanel, BorderLayout.CENTER);

        // 底部按钮
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        JButton connectButton = new JButton("连接");
        connectButton.setBounds(0, 0, 80, 30);
        connectButton.setActionCommand("connect");
        connectButton.addActionListener(this);
        JButton resetButton = new JButton("重置");
        resetButton.setBounds(0, 0, 80, 30);
        resetButton.setActionCommand("reset");
        resetButton.addActionListener(this);
        JButton exitButton = new JButton("退出");
        exitButton.setBounds(0, 0, 80, 30);
        exitButton.setActionCommand("exit");
        exitButton.addActionListener(this);
        buttonPanel.add(connectButton);
        buttonPanel.add(resetButton);
        buttonPanel.add(exitButton);

        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        // 创建头像选择面板
        avatarPanel = new JPanel();
        avatarPanel.setLayout(new GridLayout(10, 10, 1, 1)); // 10行10列，间距为1
        // 假设你有85个头像图标
        for (int i = 1; i <= 85; i++) {
            String imagePath = "picture/face/" + i + "-" + 1 + ".gif";
            JButton avatarButton = new JButton(new ImageIcon(imagePath));
            // 设置按钮的首选大小
            avatarButton.setPreferredSize(new Dimension(38, 38)); // 设置为30x30像素
            avatarButton.addActionListener(new AvatarButtonListener(imagePath));

            avatarPanel.add(avatarButton);
        }
        // 将头像选择面板添加到主面板的下方
        mainPanel.add(avatarPanel, BorderLayout.SOUTH);
        setVisible(true);
    }

    //连接方法
    private void onConnectButtonClick() throws IOException {
        String username = usernameField.getText().trim();
        String serverAddress = serverField.getText().trim();
        if (username.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写用户名和服务器地址", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (socket == null) {
            socket = SocketUtil.createLocalHost(8888);
        }
        User user = new User(username, avatarPath, serverAddress,null);
        MyMessage myMessage = new MyMessage();
        myMessage.setType(MyMessage.Type.CONNECT);
        myMessage.setContent(user);
        userFileManager = new UserFileManager();
        userFileManager.writeUser(user);
        myMessage.setFrom(username);
        SocketUtil.send(socket, myMessage);
        Object response = SocketUtil.receive(socket);
        System.out.println(response);
        if (response instanceof MyMessage) {
            MyMessage resp = (MyMessage) response;
            if (resp.getType() == MyMessage.Type.SUCCESS) {
                //登录成功
                //隐藏登录页面，跳转到游戏大厅
                LoginFrame.this.dispose();
                new GameLobby(socket, username);
            }
        }
    }

    //重置方法
    private void onResetButtonClick() {
        usernameField.setText("");
        serverField.setText("");
        avatarLabel.setIcon(new ImageIcon("picture/face/1-1.gif")); // 恢复默认头像
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        switch (cmd) {
            case "connect":
                try {
                    onConnectButtonClick();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                break;
            case "reset":
                onResetButtonClick();
                break;
            case "exit":
                System.exit(0);
                break;
            default:
                break;
        }
    }

    private class AvatarButtonListener implements ActionListener {
        private String imagePath;

        public AvatarButtonListener(String imagePath) {
            this.imagePath = imagePath;
        }


        @Override
        public void actionPerformed(ActionEvent e) {
            avatarLabel.setIcon(new ImageIcon(imagePath));
            avatarPath = imagePath;
            JOptionPane.showMessageDialog(LoginFrame.this, "头像已选择");
        }
    }

    public static void main(String[] args) {
        new LoginFrame();
    }
}